package com.ps.controller;


import com.ps.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class LoginController {

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/login")
    public String login(String usercode,String password){
        UsernamePasswordToken token=new UsernamePasswordToken(usercode,password);
        Subject subject=SecurityUtils.getSubject();
        subject.login(token);
        User loginUser= (User) subject.getPrincipal();
        subject.getSession().setAttribute("loginUser",loginUser);
        return "redirect:/index";
    }

    @ExceptionHandler(Exception.class)
    public String catchEx(Exception e, Model model){
        if(e instanceof UnknownAccountException || e instanceof IncorrectCredentialsException){
            model.addAttribute("LoginError","账号或密码错误！");
            return "login";
        }else {
            return "index";
        }
    }

}
